package rad.framework.web;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.annotations.web.Filter;
import org.jboss.seam.util.EnumerationEnumeration;
import org.jboss.seam.web.AbstractFilter;

/**
 * Adapts the Tuckey URLRewrite filter to the Seam filter chain. 
 * From Seam Wiki example.
 */
@Startup
@Scope(ScopeType.APPLICATION)
@Name("urlRewriteFilter")
@BypassInterceptors
@Filter(within = "org.jboss.seam.web.rewriteFilter")
@Install(value=false, classDependencies = "org.tuckey.web.filters.urlrewrite.UrlRewriteFilter", precedence = Install.BUILT_IN)
public class UrlRewriteFilter extends AbstractFilter {

	private org.tuckey.web.filters.urlrewrite.UrlRewriteFilter urlRewriteFilter;

	public void init(FilterConfig filterConfig) throws ServletException {
		urlRewriteFilter = new org.tuckey.web.filters.urlrewrite.UrlRewriteFilter();
		urlRewriteFilter.init(new FilterConfigWrapper(filterConfig,
				getInitParameters()));
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		urlRewriteFilter.doFilter(servletRequest, servletResponse, filterChain);
	}

	private Map<String, String> initParameters;

	public Map<String, String> getInitParameters() {
		return initParameters;
	}

	public void setInitParameters(Map<String, String> initParameters) {
		this.initParameters = initParameters;
	}

	private class FilterConfigWrapper implements FilterConfig {

		private FilterConfig delegate;
		private Map<String, String> parameters;

		public FilterConfigWrapper(FilterConfig filterConfig,
				Map<String, String> initParameters) {
			delegate = filterConfig;
			parameters = initParameters;
		}

		public String getFilterName() {
			return delegate.getFilterName();
		}

		public String getInitParameter(String name) {
			if (parameters.containsKey(name)) {
				return parameters.get(name);
			} else {
				return delegate.getInitParameter(name);
			}
		}

		public Enumeration getInitParameterNames() {
			Enumeration[] enumerations = { delegate.getInitParameterNames(),
					Collections.enumeration(parameters.keySet()) };
			return new EnumerationEnumeration(enumerations);
		}

		public ServletContext getServletContext() {
			return delegate.getServletContext();
		}
	}

}
